package com.xplay.xpocker.socket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @Author: wanjie
 * @Date: 2019/5/17 14:54
 * @Version 1.0
 */
@Slf4j
@Component
public class WebSocketServer {
    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;
    private ServerBootstrap serverBootstrap;

    @PreDestroy
    public void destroy() {
        Future<?> future = mainGroup.shutdownGracefully();
        Future<?> future1 = subGroup.shutdownGracefully();
        future.syncUninterruptibly();
        future1.syncUninterruptibly();
    }

    //开启服务器
    @PostConstruct
    public void start() {
        try {
            log.debug("start socket... ...");
            mainGroup = new NioEventLoopGroup();
            subGroup = new NioEventLoopGroup();
            serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(mainGroup, subGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            // 5.0.0.Alpha1 报错  channel(NioServerSocketChannel.class)
            //连接数
        /* serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        //不延迟，消息立即发送
        serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
        //长连接
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);*/
            serverBootstrap.childHandler(new WSServerInitialzer());
            //serverBootstrap.bind(8989);
            log.debug("start socket success");
            serverBootstrap.bind(9999).sync();
            //this.channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
